const { formatTime } = require('../../utils/util.js')
const { getApiUrl } = require('../../config/config.js')
const app = getApp()

Page({
  data: {
    keyword: '',
    searchResults: {
      posts: [],
      users: []
    },
    hotSearches: [],
    searchHistory: [],
    showSearchResult: false,
    searching: false,
    showClearHistoryConfirm: false,
    searchValue: '', // 搜索框的值
    searchHistory: [], // 搜索历史
    hotSearches: [], // 热门搜索
    searchResults: [], // 搜索结果
    showSearchResults: false, // 是否显示搜索结果
    suggestions: [], // 搜索建议
    showSuggestions: false, // 是否显示搜索建议
    loading: false, // 加载状态
    page: 1, // 当前页码
    hasMore: true, // 是否还有更多结果

    // 新增数据
    currentTab: 'all', // 当前分类标签: all/post/user/activity/topic
    tabs: [
      { key: 'all', name: '全部' },
      { key: 'post', name: '帖子' },
      { key: 'user', name: '用户' },
      { key: 'activity', name: '活动' },
      { key: 'topic', name: '话题' }
    ],
    sortType: 'relevance', // 排序方式: relevance/time/hot
    sortOptions: [
      { key: 'relevance', name: '相关度' },
      { key: 'time', name: '最新' },
      { key: 'hot', name: '热度' }
    ],
    showFilter: false, // 是否显示高级筛选
    filterOptions: {
      timeRange: 'all', // 时间范围: all/week/month
      userType: 'all', // 发布者身份: all/student/official
      tags: [] // 内容标签
    },
    skeletonLoading: true // 骨架屏加载状态
  },

  onLoad() {
    // 加载搜索历史和热门搜索
    this.loadSearchHistory()
    this.loadHotSearches()
  },

  // 加载搜索历史
  async loadSearchHistory() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return // 未登录时不加载历史记录
    
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/search/history/${userInfo.id}`),
          method: 'GET',
          success: resolve,
          fail: reject
        })
      })

      if (res.data.code === 200) {
        this.setData({
          searchHistory: res.data.data || []
        })
      }
    } catch (error) {
      console.error('Load search history failed:', error)
    }
  },

  // 加载热门搜索
  async loadHotSearches() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl('/search/hot'),
          method: 'GET',
          success: resolve,
          fail: reject
        })
      })

      if (res.data && res.data.code === 200) {
        this.setData({ hotSearches: res.data.data })
      }
    } catch (error) {
      console.error('Load hot searches failed:', error)
    }
  },

  // 输入关键词
  onInput(e) {
    this.setData({ keyword: e.detail.value.trim() })
  },

  // 清空输入
  clearInput() {
    this.setData({
      keyword: '',
      showSearchResult: false
    })
  },

  // 执行搜索
  async doSearch(keyword = this.data.keyword) {
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      })
      return
    }

    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return

    this.setData({ 
      searching: true,
      keyword,
      showSearchResult: true
    })

    try {
      // 处理搜索历史
      this.updateSearchHistory(keyword)
      
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl('/search'),
          method: 'GET',
          data: {
            keyword,
            userId: userInfo.id
          },
          success: resolve,
          fail: reject
        })
      })

      if (res.data && res.data.code === 200) {
        // 格式化帖子时间，只显示年月日
        const formattedResults = { ...res.data.data }
        
        if (formattedResults.posts && formattedResults.posts.length > 0) {
          formattedResults.posts = formattedResults.posts.map(post => {
            if (post.createTime) {
              // 将时间格式化为年月日
              const date = new Date(post.createTime)
              post.createTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
            }
            return post
          })
        }
        
        this.setData({ searchResults: formattedResults })
      } else {
        wx.showToast({
          title: '搜索失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('Search failed:', error)
      wx.showToast({
        title: '搜索失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ searching: false })
    }
  },

  // 点击搜索按钮
  onSearch() {
    this.doSearch()
  },

  // 点击热门搜索词或历史记录
  onTapKeyword(e) {
    const { keyword } = e.currentTarget.dataset
    this.setData({ keyword }, () => {
      this.doSearch()
    })
  },

  // 显示清除历史确认框
  showClearConfirm() {
    this.setData({
      showClearHistoryConfirm: true
    })
  },

  // 清除搜索历史
  async clearHistory() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/search/history/${userInfo.id}`),
          method: 'DELETE',
          success: resolve,
          fail: reject
        })
      })

      if (res.data && res.data.code === 200) {
        this.setData({
          searchHistory: [],
          showClearHistoryConfirm: false
        })
        wx.showToast({ title: '清除成功', icon: 'success' })
      } else {
        throw new Error('清除失败')
      }
    } catch (error) {
      console.error('Clear history failed:', error)
      wx.showToast({
        title: '清除失败，请重试',
        icon: 'none'
      })
    }
  },

  // 取消清除历史
  cancelClear() {
    this.setData({
      showClearHistoryConfirm: false
    })
  },

  // 点击搜索结果
  onTapResult(e) {
    const { type, id } = e.currentTarget.dataset
    if (type === 'post') {
      wx.navigateTo({
        url: `/pages/details/details?id=${id}`,
        success: () => {
          // 标记需要刷新帖子列表
          getApp().globalData.needRefreshPosts = true
        }
      })
    } else if (type === 'user') {
      wx.navigateTo({
        url: `/pages/user/user?id=${id}`
      })
    }
  },

  // 输入框变化
  onSearchInput(e) {
    const value = e.detail.value.trim()
    this.setData({ 
      searchValue: value,
      showSuggestions: value.length > 0
    })
    if (value) {
      this.getSuggestions(value)
    }
  },


  // 切换分类标签
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ 
      currentTab: tab,
      page: 1,
      searchResults: []
    })
    if (this.data.searchValue) {
      this.doSearch()
    }
  },

  // 切换排序方式
  onSortChange(e) {
    const sort = e.currentTarget.dataset.sort
    this.setData({ 
      sortType: sort,
      page: 1,
      searchResults: []
    })
    if (this.data.searchValue) {
      this.doSearch()
    }
  },

  // 显示/隐藏高级筛选
  toggleFilter() {
    this.setData({ showFilter: !this.data.showFilter })
  },

  // 应用筛选条件
  applyFilter(e) {
    const { timeRange, userType, tags } = e.detail
    this.setData({ 
      filterOptions: { timeRange, userType, tags },
      showFilter: false,
      page: 1,
      searchResults: []
    })
    if (this.data.searchValue) {
      this.doSearch()
    }
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = wx.getStorageSync('searchHistory') || []
    history = history.filter(item => item !== keyword)
    history.unshift(keyword)
    history = history.slice(0, 10)
    wx.setStorageSync('searchHistory', history)
    this.setData({ searchHistory: history })
  },

  // 添加返回方法
  backToSearch() {
    this.setData({
      showSearchResult: false,
      keyword: '',
      searchResults: {
        posts: [],
        users: []
      }
    })
  },

  // 添加点击作者事件处理
  onTapAuthor(e) {
    const { id } = e.currentTarget.dataset
    if (!id) return
    wx.navigateTo({
      url: `/pages/user/user?id=${id}`
    })
  },

  // 更新搜索历史（确保不重复且最新的在前面）
  updateSearchHistory(keyword) {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) return
    
    // 获取当前的搜索历史
    let history = [...this.data.searchHistory]
    
    // 如果关键词已存在，先移除它
    history = history.filter(item => item !== keyword)
    
    // 将新的关键词添加到最前面
    history.unshift(keyword)
    
    // 限制历史记录数量（保留最新的10条）
    if (history.length > 10) {
      history = history.slice(0, 10)
    }
    
    // 更新本地数据
    this.setData({ searchHistory: history })
    
    // 同时更新到服务器
    this.saveSearchHistoryToServer(keyword, userInfo.id)
  },

  // 保存搜索历史到服务器
  async saveSearchHistoryToServer(keyword, userId) {
    try {
      await new Promise((resolve, reject) => {
        wx.request({
          url: getApiUrl(`/search/history/${userId}`),
          method: 'GET',  // 使用POST方法添加新的搜索历史
          data: {
            keyword
          },
          success: resolve,
          fail: reject
        })
      })
    } catch (error) {
      console.error('Save search history failed:', error)
    }
  },

}) 